package sanbing.jcpplearning;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;

public class ByteBufCategoryExample {
    public static void main(String[] args) {
        // 1. Heap Buffer: 使用堆内存分配，适合频繁操作数据的场景
        ByteBuf heapBuffer = Unpooled.buffer(64); // 创建一个堆内存的缓冲区
        heapBuffer.writeBytes("Hello from HeapBuffer".getBytes());
        System.out.println("HeapBuffer内容: " + heapBuffer.toString(io.netty.util.CharsetUtil.UTF_8));
        System.out.println("HeapBuffer类型: " + heapBuffer.getClass().getName());
        heapBuffer.release(); // 释放内存（非池化的缓冲区需要手动释放）

        // 2. Direct Buffer: 使用堆外内存分配，适合高性能 I/O 场景
        ByteBuf directBuffer = Unpooled.directBuffer(64); // 创建一个堆外内存的缓冲区
        directBuffer.writeBytes("Hello from DirectBuffer".getBytes());
        System.out.println("DirectBuffer内容: " + directBuffer.toString(io.netty.util.CharsetUtil.UTF_8));
        System.out.println("DirectBuffer类型: " + directBuffer.getClass().getName());
        directBuffer.release(); // 释放内存，防止内存泄漏

        // 3. Composite Buffer: 组合多个 ByteBuf，适合分片数据处理
        CompositeByteBuf compositeBuffer = ByteBufAllocator.DEFAULT.compositeBuffer(); // 创建一个 CompositeByteBuf
        ByteBuf part1 = Unpooled.buffer(32);
        ByteBuf part2 = Unpooled.buffer(32);
        part1.writeBytes("Part1: Hello ".getBytes());
        part2.writeBytes("Part2: World!".getBytes());
        compositeBuffer.addComponents(true, part1, part2); // 将两个 ByteBuf 添加到 CompositeByteBuf
        System.out.println("CompositeBuffer内容: " + compositeBuffer.toString(io.netty.util.CharsetUtil.UTF_8));
        System.out.println("CompositeBuffer类型: " + compositeBuffer.getClass().getName());
        compositeBuffer.release(); // 释放 CompositeBuffer，会自动释放其子组件

        // 4. Pooled Buffer: 使用池化内存分配，适合高并发场景
        ByteBuf pooledBuffer = ByteBufAllocator.DEFAULT.buffer(64); // 默认分配池化的缓冲区
        pooledBuffer.writeBytes("Hello from PooledBuffer".getBytes());
        System.out.println("PooledBuffer内容: " + pooledBuffer.toString(io.netty.util.CharsetUtil.UTF_8));
        System.out.println("PooledBuffer类型: " + pooledBuffer.getClass().getName());
        pooledBuffer.release(); // 释放内存，池化缓冲区仍会被回收到内存池中

        // 5. Unpooled Buffer: 临时的非池化缓冲区，用于临时操作
        ByteBuf unpooledBuffer = Unpooled.buffer(64); // 创建一个非池化缓冲区
        unpooledBuffer.writeBytes("Hello from UnpooledBuffer".getBytes());
        System.out.println("UnpooledBuffer内容: " + unpooledBuffer.toString(io.netty.util.CharsetUtil.UTF_8));
        System.out.println("UnpooledBuffer类型: " + unpooledBuffer.getClass().getName());
        unpooledBuffer.release(); // 释放内存
    }
}